from datetime import datetime, timedelta, timezone
from typing import Union

import pytz
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from fastapi_amis_admin.globals.deps import SyncSess
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from sqlalchemy import text
from superstream import Stream

from backend.apps.common import cache, AppException, AppBaseModel
from backend.apps.user.models import SysUser
from backend.apps.security.models import SecurityUser
from backend.core.settings import settings
import json



tz = pytz.timezone('Asia/Shanghai')

# to get a string like this run:
# openssl rand -hex 32
SECRET_KEY = settings.openssl_secret_key
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

class Token(BaseModel):
    access_token: str
    token_type: str


class TokenData(BaseModel):
    username: Union[str, None] = None


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/oauth/token")


def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)


def get_password_hash(password):
    return pwd_context.hash(password)


def get_user(sses: SyncSess, username: str) -> SecurityUser:
    securityUserStr = cache.get(username)
    if securityUserStr:
        securityUserDict = json.loads(securityUserStr)
        cache.expire(username, 3600)
        return SecurityUser(**securityUserDict)
    user = sses.query(SysUser).filter(SysUser.username == username).scalar()
    if not user:
        raise AppException(err_msg="用户不存在！")
    securityUser = SecurityUser(id=user.id, username=user.username,
                                password=user.password, realName=user.real_name,
                                headUrl=user.head_url, superAdmin=user.super_admin,
                                status=user.status, depts=[], roles=[], principals=[])
    if user.super_admin == 1:
        securityUser.principals = get_admin_permissions(sess=sses)
    else:
        securityUser.principals = get_user_permissions(userId=user.id, sess=sses)
    print(securityUser.json())
    cache.set(username, securityUser.json(), 3600)
    return securityUser

def get_admin_permissions(sess:SyncSess):
    stmt = text('''
    select t3.permissions from sys_menu t3 where t3.permissions is not NULL AND t3.permissions != ''
    ''')
    result = sess.execute(stmt).all()
    list = Stream(result).map(lambda e: e[0]).to_list()
    return list

def get_user_permissions(userId:int, sess:SyncSess):
    stmt = text('''
    select t3.permissions
        from sys_role_user t1
            left join sys_role_menu t2 on t1.role_id = t2.role_id
            left join sys_menu t3 on t2.menu_id = t3.id
        where t1.user_id = :userId
        and t3.permissions is not NULL AND t3.permissions != ''
        order by t3.sort asc
    ''').bindparams(userId=userId)
    result = sess.execute(stmt).all()
    list = Stream(result).map(lambda e: e[0]).to_list()
    return list


def authenticate_user(sses: SyncSess, username: str, password: str):
    user = get_user(sses, username)
    if not user:
        return False
    if not verify_password(password, user.password):
        return False
    return user


def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None):
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt


async def get_current_user(sses: SyncSess, token: str = Depends(oauth2_scheme)):
    credentials_exception = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Could not validate credentials",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str = payload.get("sub")
        if username is None:
            raise credentials_exception
        token_data = TokenData(username=username)
    except JWTError:
        raise credentials_exception
    user = get_user(sses, username=token_data.username)
    if user is None:
        raise credentials_exception
    return user


async def get_current_active_user(current_user: SecurityUser = Depends(get_current_user)):
    if not current_user.status:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user



from fastapi_permissions import (
    Allow,
    Authenticated,
    Everyone,
    configure_permissions,
)

def get_active_principals(user: SecurityUser = Depends(get_current_user)):
    if user:
        # user is logged in
        principals = [Everyone, Authenticated]
        principals.extend(getattr(user, "principals", []))
    else:
        # user is not logged in
        principals = [Everyone]
    return principals


Permission = configure_permissions(get_active_principals)

def get_principals(user=Depends(get_current_user)):
    principals = []
    for principal in user.principals:
        principals.append((Allow, Authenticated, principal))
    return principals

